<template>
  <div class="order-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>订单列表</span>
          <div class="header-actions">
            <el-select v-model="statusFilter" placeholder="订单状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="待付款" value="pending" />
              <el-option label="已付款" value="paid" />
              <el-option label="已发货" value="shipped" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="filteredOrders"
        style="width: 100%"
      >
        <el-table-column prop="orderNo" label="订单编号" width="180" />
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="handleView(row)"
              >
                查看
              </el-button>
              <el-button
                v-if="row.status === 'pending'"
                type="success"
                size="small"
                @click="handlePay(row)"
              >
                付款
              </el-button>
              <el-button
                v-if="row.status === 'paid'"
                type="warning"
                size="small"
                @click="handleShip(row)"
              >
                发货
              </el-button>
              <el-button
                v-if="row.status === 'pending'"
                type="danger"
                size="small"
                @click="handleCancel(row)"
              >
                取消
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @update:current-page="handleCurrentChange"
          @update:page-size="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="订单详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">
          {{ selectedOrder.orderNo }}
        </el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(selectedOrder.status)">
            {{ getStatusText(selectedOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="商品名称">
          {{ selectedOrder.productName }}
        </el-descriptions-item>
        <el-descriptions-item label="商品单价">
          ¥{{ selectedOrder.productPrice?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="购买数量">
          {{ selectedOrder.quantity }}
        </el-descriptions-item>
        <el-descriptions-item label="总金额">
          ¥{{ selectedOrder.totalAmount?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="收货人">
          {{ selectedOrder.receiverName }}
        </el-descriptions-item>
        <el-descriptions-item label="联系电话">
          {{ selectedOrder.receiverPhone }}
        </el-descriptions-item>
        <el-descriptions-item label="收货地址" :span="2">
          {{ selectedOrder.receiverAddress }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(selectedOrder.createdAt) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(selectedOrder.updatedAt) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useStore()
const loading = ref(false)
const orders = ref([])
const dialogVisible = ref(false)
const selectedOrder = ref({})
const statusFilter = ref('')
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const filteredOrders = computed(() => {
  let result = [...orders.value]
  
  if (statusFilter.value) {
    result = result.filter(order => order.status === statusFilter.value)
  }
  
  if (dateRange.value && dateRange.value.length === 2) {
    const [startDate, endDate] = dateRange.value
    result = result.filter(order => {
      const orderDate = new Date(order.createdAt).toISOString().split('T')[0]
      return orderDate >= startDate && orderDate <= endDate
    })
  }
  
  return result
})

const getStatusType = (status) => {
  const statusMap = {
    pending: 'warning',
    paid: 'primary',
    shipped: 'success',
    completed: 'success',
    cancelled: 'info'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

const fetchOrders = async () => {
  try {
    loading.value = true
    const data = await store.dispatch('order/getOrders', {
      page: currentPage.value,
      pageSize: pageSize.value
    })
    orders.value = data.items
    total.value = data.total
  } catch (error) {
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

const handleView = (row) => {
  selectedOrder.value = row
  dialogVisible.value = true
}

const handlePay = (row) => {
  ElMessageBox.confirm(
    '确定要支付该订单吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await store.dispatch('order/updateOrderStatus', {
        id: row.id,
        status: 'paid'
      })
      ElMessage.success('支付成功')
      fetchOrders()
    } catch (error) {
      ElMessage.error('支付失败')
    }
  })
}

const handleShip = (row) => {
  ElMessageBox.confirm(
    '确定要发货吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await store.dispatch('order/updateOrderStatus', {
        id: row.id,
        status: 'shipped'
      })
      ElMessage.success('发货成功')
      fetchOrders()
    } catch (error) {
      ElMessage.error('发货失败')
    }
  })
}

const handleCancel = (row) => {
  ElMessageBox.confirm(
    '确定要取消该订单吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await store.dispatch('order/updateOrderStatus', {
        id: row.id,
        status: 'cancelled'
      })
      ElMessage.success('取消成功')
      fetchOrders()
    } catch (error) {
      ElMessage.error('取消失败')
    }
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrders()
}

onMounted(() => {
  fetchOrders()
})
</script>

<style lang="scss" scoped>
.order-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 